#!/usr/bin/env python3
"""
演示如何获取 Stripe Customer Portal URL
"""

import stripe
import requests
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import logging

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 配置Stripe
stripe.api_key = "sk_test_51Ogsw5B0IyqaSJBrwczlr820jnmvA1qQQGoLZ2XxOsIzikpmXo4pRLjw4XVMTEBR8DdVTYySiAv1XX53Zv5xqynF00GfMqttFd"

app = FastAPI()

class PortalSessionRequest(BaseModel):
    customer_id: str
    return_url: str = "http://localhost:8002/portal-return"

@app.post("/create-portal-session")
async def create_portal_session(request: PortalSessionRequest):
    """
    创建 Customer Portal 会话并获取 URL
    
    这是获取 Customer Portal URL 的标准方法
    """
    try:
        # 创建 Customer Portal 会话
        session = stripe.billing_portal.Session.create(
            customer=request.customer_id,
            return_url=request.return_url,
            configuration=None  # 使用默认配置
        )
        
        logger.info(f"创建 Customer Portal 会话成功: {session.id}")
        
        return {
            "session_id": session.id,
            "url": session.url,  # 这就是 Customer Portal 的 URL
            "customer_id": request.customer_id
        }
        
    except stripe.error.StripeError as e:
        logger.error(f"创建 Customer Portal 会话失败: {str(e)}")
        raise HTTPException(status_code=400, detail=f"创建 Portal 会话失败: {str(e)}")
    except Exception as e:
        logger.error(f"服务器错误: {str(e)}")
        raise HTTPException(status_code=500, detail="服务器内部错误")

@app.get("/portal-return")
async def portal_return():
    """
    Customer Portal 返回页面
    用户从 Customer Portal 返回后会跳转到这里
    """
    return {
        "status": "success",
        "message": "您已从 Customer Portal 返回",
        "description": "用户可以在 Portal 中管理订阅、支付方式等"
    }

# 演示函数
def demonstrate_portal_url():
    """
    演示如何获取 Customer Portal URL
    """
    print("🎯 Stripe Customer Portal URL 获取演示")
    print("=" * 60)
    
    # 示例客户ID（需要替换为真实的客户ID）
    customer_id = "cus_example_customer_id"
    
    try:
        # 方法1: 使用 Stripe Python SDK
        print("方法1: 使用 Stripe Python SDK")
        print("-" * 40)
        
        session = stripe.billing_portal.Session.create(
            customer=customer_id,
            return_url="http://localhost:8002/portal-return"
        )
        
        print(f"✅ Portal URL: {session.url}")
        print(f"   会话ID: {session.id}")
        print(f"   客户ID: {customer_id}")
        
        # 方法2: 使用 HTTP API
        print("\n方法2: 使用 HTTP API")
        print("-" * 40)
        
        api_url = "https://api.stripe.com/v1/billing_portal/sessions"
        headers = {
            "Authorization": f"Bearer {stripe.api_key}",
            "Content-Type": "application/x-www-form-urlencoded"
        }
        data = {
            "customer": customer_id,
            "return_url": "http://localhost:8002/portal-return"
        }
        
        response = requests.post(api_url, headers=headers, data=data)
        result = response.json()
        
        if response.status_code == 200:
            print(f"✅ Portal URL: {result['url']}")
            print(f"   会话ID: {result['id']}")
        else:
            print(f"❌ 请求失败: {result.get('error', {}).get('message', '未知错误')}")
            
    except stripe.error.StripeError as e:
        print(f"❌ Stripe 错误: {str(e)}")
    except Exception as e:
        print(f"❌ 服务器错误: {str(e)}")
    
    print("\n" + "=" * 60)
    print("📋 使用说明:")
    print("1. 将 customer_id 替换为真实的客户ID")
    print("2. 确保 Stripe 账户已启用 Customer Portal")
    print("3. 在浏览器中打开返回的 URL")
    print("4. 用户可以在 Portal 中管理订阅和支付方式")

if __name__ == "__main__":
    demonstrate_portal_url()
